<template>
  <div class="tickets-view">
    <h1>🎫 票务管理</h1>

    <el-card class="toolbar-card">
      <div class="toolbar">
        <el-input v-model="query.keyword" placeholder="关键词（票种/演出ID）" clearable class="w-300" @keyup.enter.native="loadTickets" />
        <el-select v-model="query.size" class="w-120" @change="handleSizeChange">
          <el-option :value="10" label="每页10条" />
          <el-option :value="20" label="每页20条" />
          <el-option :value="50" label="每页50条" />
        </el-select>
        <el-button type="primary" @click="loadTickets" :loading="loading">查询</el-button>
        <el-button @click="resetFilters" :disabled="loading">重置</el-button>
        <el-button type="success" @click="openCreate">新增票务</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="tickets" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="eventId" label="演出ID" width="100" />
        <el-table-column prop="ticketType" label="票种" min-width="160" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">¥{{ row.price ?? 0 }}</template>
        </el-table-column>
        <el-table-column prop="seatArea" label="区域" width="120" />
        <el-table-column prop="seatRow" label="排" width="100" />
        <el-table-column prop="seatNumber" label="座位" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : (row.status === 0 ? 'info' : (row.status === 2 ? 'warning' : 'default'))">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editTicket(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeTicket(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="query.size"
          :current-page="query.page + 1"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑票务' : '新增票务'" width="600">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="演出ID" prop="eventId"><el-input v-model="form.eventId" /></el-form-item>
      <el-form-item label="票种" prop="ticketType"><el-input v-model="form.ticketType" /></el-form-item>
      <el-form-item label="价格" prop="price"><el-input v-model.number="form.price" /></el-form-item>
      <el-form-item label="区域" prop="seatArea"><el-input v-model="form.seatArea" /></el-form-item>
      <el-form-item label="排" prop="seatRow"><el-input v-model="form.seatRow" /></el-form-item>
      <el-form-item label="座位" prop="seatNumber"><el-input v-model="form.seatNumber" /></el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status">
          <el-option label="在售(1)" :value="1" />
          <el-option label="不可售(0)" :value="0" />
          <el-option label="已售(2)" :value="2" />
          <el-option label="锁定(3)" :value="3" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submitTicket">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ticketAPI } from '@/api'

const loading = ref(false)
const tickets = ref([])
const total = ref(0)
const query = ref({ page: 0, size: 10, keyword: '' })

// 编辑弹窗
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref(null)
const form = ref({ id: null, eventId: '', ticketType: '', price: 0, seatArea: '', seatRow: '', seatNumber: '', status: 1 })
const rules = {
  eventId: [{ required: true, message: '请输入演出ID', trigger: 'blur' }],
  ticketType: [{ required: true, message: '请输入票种', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

async function loadTickets() {
  try {
    loading.value = true
    const resp = await ticketAPI.getTicketList({ ...query.value })
    const content = resp?.data?.content || resp?.content || resp || []
    tickets.value = Array.isArray(content) ? content : []
    total.value = resp?.data?.totalElements ?? resp?.totalElements ?? tickets.value.length
  } catch (err) {
    ElMessage.error(`加载票务失败：${err?.message || '请求错误'}`)
  } finally {
    loading.value = false
  }
}

function resetFilters() { query.value = { page: 0, size: 10, keyword: '' }; loadTickets() }
function handleSizeChange() { query.value.page = 0; loadTickets() }
function handlePageChange(p) { query.value.page = p - 1; loadTickets() }

function editTicket(row) {
  isEdit.value = true
  form.value = { id: row.id, eventId: row.eventId, ticketType: row.ticketType, price: row.price, seatArea: row.seatArea, seatRow: row.seatRow, seatNumber: row.seatNumber, status: row.status ?? 1 }
  dialogVisible.value = true
}
function openCreate() {
  isEdit.value = false
  form.value = { id: null, eventId: '', ticketType: '', price: 0, seatArea: '', seatRow: '', seatNumber: '', status: 1 }
  dialogVisible.value = true
}
async function submitTicket() {
  try {
    await formRef.value.validate()
    saving.value = true
    if (isEdit.value && form.value.id) {
      await ticketAPI.updateTicket(form.value.id, { ...form.value })
      ElMessage.success('票务已更新')
    } else {
      await ticketAPI.createTicket({ ...form.value })
      ElMessage.success('票务已创建')
    }
    dialogVisible.value = false
    loadTickets()
  } catch (err) {
    ElMessage.error(err?.message || '保存失败')
  } finally {
    saving.value = false
  }
}
async function removeTicket(row) {
  try {
    await ElMessageBox.confirm(`确认删除票务「${row.ticketType || row.id}」吗？`, '提示', { type: 'warning' })
    await ticketAPI.deleteTicket(row.id)
    ElMessage.success('已删除')
    loadTickets()
  } catch (err) {
    if (String(err).includes('cancel')) return
    ElMessage.error(err?.message || '删除失败')
  }
}

onMounted(loadTickets)

function formatStatus(s) {
  switch (s) {
    case 1: return '在售'
    case 2: return '已售'
    case 3: return '锁定'
    case 0: return '不可售'
    default: return '未知'
  }
}
</script>

<style scoped>
.tickets-view { padding: 20px; }
.toolbar-card { margin-bottom: 12px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
.w-300 { width: 300px; }
.w-120 { width: 120px; }
.table-footer { display: flex; justify-content: flex-end; padding-top: 12px; }
</style>